package cn.chowx.myjfinal.system.model;


import org.apache.commons.lang3.math.NumberUtils;

import cn.chowx.myjfinal.common.TableName;

import com.jfinal.plugin.activerecord.Model;

/**
 * 角色-资源映射
 * @author zcqshine
 *
 */
@SuppressWarnings("serial")
public class SysRoleAction extends Model<SysRoleAction> {	
	public static final SysRoleAction DAO = new SysRoleAction();
	private static final int STATUS_VALIABLE = 1;  //有效状态
	private static final int STATUS_UNVALIABLE = 0; //无效状态
	/**
	 * 新增或更新角色拥有的资源.操作成功返回 true, 失败返回 false
	 * @param roleId
	 * @param actIdAndChk actionId:checked 键值对
	 * @return
	 */
	public boolean saveOrUpdate(int roleId, String[] actIdAndChk){
		boolean flag = false;
		for(String kv : actIdAndChk){
			int actionId = NumberUtils.toInt(kv.split(":")[0]);
			boolean checked = Boolean.parseBoolean(kv.split(":")[1]);
			SysRoleAction ra = getRoleActionByRoleIdAndActionId(roleId,actionId);
			/*
			 * 如果存在映射关系则改变状态,不存在映射关系则添加映射关系
			 */
			if(actionId > 1){	//不能将根节点资源赋予角色,否则会导致导航菜单出问题
				if(ra != null){	
					ra.set("status",checked?STATUS_VALIABLE:STATUS_UNVALIABLE);
					flag = ra.update();
				}else{
					ra = new SysRoleAction();
					ra.set("roleId", roleId);
					ra.set("actionId", actionId);
					ra.set("status", checked?STATUS_VALIABLE:STATUS_UNVALIABLE);
					flag = ra.save();
				}
				if(!flag)
					return flag;
			}
		}
		return flag;
	}
	
	/**
	 * 根据角色 ID, 资源 id 获取角色-资源映射关系对象
	 * @param roleId	角色 id
	 * @param actionId	资源 id
	 * @return SysRoleAction
	 */
	private SysRoleAction getRoleActionByRoleIdAndActionId(int roleId, int actionId){
		return findFirst("select * from "+ TableName.SysRoleAction.getTableName() + " where roleId = ? and actionId = ?",roleId, actionId); 
	}
}
